<?php
declare(strict_types=1);

namespace SixShop\Lakala\Model;

use app\model\User;
use SixShop\Lakala\Enum\ReceiverActionEnum;
use SixShop\Lakala\Enum\ReceiverStatusEnum;
use SixShop\Payment\Enum\NumberBizEnum;
use think\db\Query;
use think\Model;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;

class ProfitShareReceiverModel extends Model
{
    use SoftDelete;

    protected function getOptions(): array
    {
        return [
            'name' => 'profit_share_receiver',
            'type' => [
                'action' => ReceiverActionEnum::class,
                'status' => ReceiverStatusEnum::class
            ],
            'insert' => ['order_no'],
            'readonly' => ['user_id', 'order_no'],
        ];
    }

    protected function setOrderNoAttr($value, $data): string
    {
        return generate_number(NumberBizEnum::PROFIT_SHARE_RECEIVER, 5);
    }

    public function getActionTextAttr($value, $data)
    {
        return $data['action']->toString();
    }

    public function getStatusTextAttr($value, $data)
    {
        return $data['status']->toString();
    }

    public function searchStatusAttr(Query $query, $value, $data)
    {
        if ($value === null) return;
        $status = ReceiverStatusEnum::tryFrom($value);
        $status && $query->where('status', $value);
    }

    public function searchOrderNoAttr(Query $query, $value, $data)
    {
        $value && $query->where('order_no', 'like', "%{$value}%");
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }
}